<template>
  <div class="plan-edit-box"
  element-loading-text="数据加载中"
  element-loading-spinner="el-icon-loading"
  v-loading="pageLoading"
  >
  <!-- v-loading="pageLoading" -->
    <div class="plan-page-header">
        <div class="header-title">{{this.title}}</div>
        <processButtons
          :disabledPage="disabledPage"
          :disabledAction="disabledAction"
          :fromPage="fromPage"
          :dataStatus="dataStatus"
          @hide="hideFun"
          @save="save"
          @submit="save"
          @modify="save"
          @withdraw="save"
          @approve="changeStatus"
          @reject="changeStatus"
        >
      </processButtons>
        <!-- <div class="header-btns">
          <RPButton optType="reset" style="margin-right: 10px"  @click="hideFun" text="取消" />
          <RPButton style="margin-right: 10px" v-if="!disabledPage && 
          ((fromPage == 'creater' && (dataStatus == 4|| dataStatus == 1 || dataStatus == 0)) ||
        (fromPage == 'Summary' && dataStatus == 3))" optType="create" type="info" @click="save('1')" text="保存" />
          <RPButton style="margin-right: 10px" v-if="!disabledPage && fromPage == 'creater' && (dataStatus == 1 || dataStatus == 0)" optType="create" type="info" @click="save('2')" text="提交" />
          <RPButton style="margin-right: 10px" v-if="!disabledPage && fromPage == 'creater' && dataStatus == 4" optType="create" type="info" @click="save('2')" text="提交修改" />
          <RPButton style="margin-right: 10px" v-if="!disabledPage && fromPage == 'creater' && dataStatus == 2" optType="create" type="info" @click="save('1')" text="撤回提交" />
          <template v-if="fromPage == 'Approver' && dataStatus == 2">
            <RPButton style="margin-right: 10px" optType="create" type="info" @click="changeStatus(true)" text="通过" />
            <RPButton style="margin-right: 10px" optType="create" type="info" @click="changeStatus(false)" text="驳回" />
          </template>
      </div> -->
    </div>
    <div class="plan-page-content">
      <div :class="id ? 'disableFontcolor' : ''">
        <Form :model="modelForm" :disabled="disabledPage || (fromPage == 'creater' && dataStatus == 2)" class="ivu-form-no-margin-bottom" ref="editForm" :rules="rule" :label-width="200">
            <template v-if="useApiGetData">
                <Row :gutter="20" class="code-row-bg">
            <Col span="24" style="border:none;">
                <Form-item prop="tableCode" label="业务单元：" >
                <Select size="small" filterable :disabled="!!this.id" v-model="modelForm.tableCode"  >
                    <Option @click.native="changetableCode(item)" v-for="item in bussinessUnit" :value="item.trgNode" :key="item.trgNode">{{item.trgNode}}</Option>
                </Select>
                </Form-item>
            </Col>
            </Row>
         
            <Row :gutter="20" class="code-row-bg">
            <Col span="24" style="border:none;">
                <Form-item prop="company" label="二级组织：">
                <Select size="small" :disabled="!!this.id"  v-model="modelForm.company" >
                    <Option @click.native="changecompany(item)" v-for="item in secondOrgan" :value="item.nodeName" :key="item.nodeName">{{item.nodeName}}</Option>
                </Select>
                </Form-item>
            </Col>
            </Row>
            <Row :gutter="20" class="code-row-bg">
              <Col span="24" style="border:none;">
                  <Form-item prop="dpt" label="三级组织：">
                    <Select size="small" :disabled="!!this.id"  v-model="modelForm.dpt" >
                      <Option  v-for="item in thirdOrgan" :value="item.nodeName" :key="item.nodeName">{{item.nodeName}}</Option>
                    </Select>
                  </Form-item>
              </Col>
            </Row>
            </template>
            <Row :gutter="20" class="code-row-bg" v-show="!disabledPage && !!!this.id">
              <Col span="24" style="border:none;">
                  <Form-item prop="code1" label="关联表：">
                    <Select style="line-height:30px" size="small" v-model="modelForm.code1" filterable
                      :remote-method="() => {}"
                      @on-query-change="getListByValue"
                      @on-clear="getListByValue"  clearable>
                      <Option v-for="item in associationTable" :value="item.id" :key="item.id">{{item.taskCode}}</Option>
                    </Select>
                  </Form-item>
              </Col>
            </Row>
            <template v-for="(item, index) in editForm">
              <p class="p1" :key="`${item.firstType}${index}`">{{item.firstType}}</p>
              <template v-for="(sedTypeList, index1) in item.children">
                <p class="p2" :key="`${index}-${index1}`">{{sedTypeList.sedType}}</p>
                <template v-for="(app, index2) in sedTypeList.children">
                  <Row :gutter="20" class="code-row-bg" :key="`${index}-${index1}-${index2}-${app.appCode}`">
                      <Col span="24" style="border:none;">
                          <Form-item
                            :prop="app.appCode"
                            :label="`${app.appName}：`" >
                            <Input v-model="modelForm[app.appCode]" :maxlength="10" :placeholder="`请输入`" />  
                          </Form-item>
                      </Col>
                  </Row>
                </template>
              </template>
            </template>
        </Form>
        </div>
    </div>
  </div>
</template>

<script>
import todoApi from '@/api/todoCender.js'
import coverApi from '@/api/cover.js'
import processButtons from '@/components/processButtons'
import { excludeHiddenBussinessUnit } from '@/tools/common.js'
import approvalOpinion from '@/components/ListView/approvalOpinion'
export default {
    components: {
      processButtons
    },
    props: {
        id: {
            type: String,
            default: ''
        },
        disabledPage: {
            type: Boolean,
            default: false
        },
        title:{
            type: String,
            default() {
                return "";
            }
        },
        type: {
            type: String,
            default() {
                return "";
            }
        },
        vsCode: {
            type: String,
            default: ''
        },
        Code:{
            type: String,
            default: ''
        },
        fromPage: {
          type: String,
          default: 'creater',
        },
        dataStatus: {
          type: Number,
          default: 0,
        },
        tableId: {
        type: String,
        default: '',
      }
    },
    data(){
        const Datas1=[
                {key:'0',value:'-'},
                {key:'1',value:'0'},
                {key:'2',value:'1'},
            ]
         const Datas2 = [
                {key:'0',value:'-'},
                {key:'2',value:'1'},
            ]
        return{
            useApiGetData: true,
            associationTable:[],
            bussinessUnit:[],
            thirdOrgan:[],
            secondOrgan:[],
            vsiDescription:'',
            pageLoading: false,
            selectValue: '',
            editForm: [],
            Datas: this.type == 'target'? Datas2 : Datas1,
            disabledAction: false,
            modelForm: {
                code1: '',
                tableCode: '',
                company: '',
                dpt: '',
            },
            rule: {
                tableCode: [{ required: true, message: "请选择业务单元", trigger: "change" }],
                company: [{ required: true, message: "请选择二级组织", trigger: "change" }],
                dpt: [{ required: false, message: "请选择三级组织", trigger: "blur" }],
            },
            
        }
    },
    mounted(){
      this.pageLoading = true
        coverApi.getRptReportTrgnodePList({reportName: "关键业务环节数字化覆盖度"}).then(res => {
          this.modelForm.tableCode = this.Code || ''
          this.bussinessUnit = res.data.data
          this.bussinessUnit = excludeHiddenBussinessUnit(this.bussinessUnit)
          this.getStatusTargetOptions()
        })
    },
    watch: {
      'modelForm.company': {
        handler(val) {
          this.$nextTick(() => {
            if (!this.modelForm.dpt) {
              if (val) {
                this.getListByCode()
              } else {
                this.associationTable = [],
                this.modelForm.code1 = null
                this.selectValue = null
              }
            }
          })
        }
      },
      'modelForm.dpt': {
        handler(val) {
          if (val) {
            this.getListByCode()
          } else {
            this.associationTable = [],
            this.modelForm.code1 = null
            this.selectValue = null
          }
        }
      },
      'modelForm.code1': {
        handler(val) {
          if (val) {
            this.pageLoading = true
            this.codeChange(val)
            // let requestApi = {
            //   // 数字化覆盖现状
            //   status: coverApi.getCoverStatusById,
            //   // 数字化覆盖目标
            //   target: coverApi.getwfRptDgcalHrhxById
            // }
            //   requestApi[this.type]({
            //     data: {
            //       id: val,
            //     },
            //     type: this.fromPage
            //   }).then(res => {
            //       let info = res.data.data
            //       this.modelForm = {
            //           code1: val || '',
            //           tableCode: info.trgNode || '',
            //           company: info.company || '',
            //           dpt: info.dpt || '',
            //       }
            //         console.log(this.bussinessUnit, )
            //         this.secondOrgan = this.bussinessUnit.find(item => item.vsiValue == this.modelForm.tableCode).children
            //         this.thirdOrgan = this.secondOrgan.find(item => item.value == this.modelForm.company) ? this.secondOrgan.find(item => item.value == this.modelForm.company).children : []

            //         this.$nextTick(() => {
            //           this.getTreeList(() => {
            //               this.pageLoading = false
            //           })
            //         })
            //     })
            // }
            
          }
        }
      },
    },
    methods:{
     async codeChange(id) {
            this.pageLoading = true
            let codeInfo = {}
            let requestApi = {
              // 数字化覆盖现状
              status: coverApi.getCoverStatusById,
              // 数字化覆盖目标
              target: coverApi.getwfRptDgcalHrhxById
            }
            await  requestApi[this.type]({
              data: {
                id: id,
              },
              type: this.fromPage
            }).then(res => {
              let info = res.data.data
              codeInfo = res.data.data
              this.modelForm = {
                  code1: id || '',
                  tableCode: info.trgNode || '',
                  company: info.company || '',
                  dpt: info.dpt || '',
              }
              
            })
            let selectData = this.bussinessUnit.find(item => item.trgNode == this.modelForm.tableCode)
            if (selectData) {
              await coverApi.getRptTrgnodeTree({parentNodeCode: selectData.nodeId}).then(second => {
                this.secondOrgan = second.data.data
              })
              let selecSecondtData = this.secondOrgan.find(item => item.nodeName == this.modelForm.company)
              if (selecSecondtData && selecSecondtData.nodeId) {
                await coverApi.getRptTrgnodeTree({parentNodeCode: selecSecondtData.nodeId}).then(three => {
                  this.thirdOrgan = three.data.data
                })
              }

            }
            this.$nextTick(() => {
              this.getTreeList(() => {
                Object.keys(this.modelForm).forEach(item => {
                  this.modelForm[item] = codeInfo[item] || this.modelForm[item]
                })
                this.pageLoading = false
              })
            })
      },
      deepList(list, obj, rule) {
        list.forEach(item => {
          if (item.treeLevel == 3 && item.appCode) {
            obj[item.appCode] = this.modelForm[item.appCode] || ''
            rule[item.appCode] = [{ required: false, validator:  (rule, value, callback) => {
              if (value && !/^[0-9-]*$/g.test(value)) {
                callback(new Error('只能输入数字和-'))
              } else if (value.length > 10) {
                callback(new Error('最大输入长度为10'))
              } else {
                callback()
              }
            }, trigger: "blur" }]
          }
          if (item.children && item.children.length) {
            this.deepList(item.children, obj, rule)
          }
        })
      },
      getTreeList(callback) {
        coverApi.getTreeList({
          trgNode: this.modelForm.tableCode
        }).then(res => {
          let treeData = res.data.data;
          this.editForm = treeData
          let obj = {}
          this.deepList(treeData, obj, this.rule)
          this.modelForm = {
            ...this.modelForm,
            ...obj
          }

          callback && callback()
        })
      },
      changeStatus() {
      //   this.$Modal.confirm({
      //     render: (h) => {
      //         return h( 'div', 
      //           {
      //             class: 'icon-box'
      //           },
      //           [
      //             h('Icon', {
      //               props: {
      //                 type: types ? 'ios-checkmark-circle' : 'ios-alert'
      //               }
      //             }),
      //             h('span', types ? '是否确定通过？': '是否确定驳回？'),
      //             h('p', types ? '通过操作不可撤销，请谨慎操作。': '驳回操作不可撤销，请谨慎操作。'),
      //           ]
      //         )
      //     },
      //     onOk: () => {
      //       this.disabledAction = true
      //       todoApi.changeRowStatus({
      //         id: this.modelForm.id,
      //         tableId: this.tableId
      //       }, types).then(() => {
      //         this.$Message.success({
      //           content: '操作成功',
      //           duration: 3
      //         })
      //         this.$emit('Close', true)
      //       }).finally(() => {
      //         this.disabledAction = false
      //       })
      //     }
      // })
      new this.$pageModal(
        approvalOpinion,
        {
          props: {
          }
        },
        async (data) => {
          if (!data) return
            this.disabledAction = true
            todoApi.changeRowStatus({
              id: this.modelForm.id,
              tableId: this.tableId,
              approverComments: data.approverComments
            }, data.result == '通过' ? true : false).then(() => {
              this.$Message.success({
                content: '操作成功',
                duration: 3
              })
              this.$emit('Close', true)
            }).finally(() => {
              this.disabledAction = false
            })
        }
      )
    },
        getListByValue(value) {
          if (this.associationTable.find(item => item.taskCode == value)) {
            return false
          }
          if (!value && !this.modelForm.dpt) {
            this.associationTable = [],
            this.modelForm.code1 = null
            this.selectValue = null
            return false
          }
          this.selectValue = value
          this.getListByCode()
        },
        getListByCode() {
          let paramsData = {
            taskCode: this.selectValue,//:"编码",
            trgNode: this.modelForm.tableCode,// "业务单元",
            company: this.modelForm.company,
            dpt: this.modelForm.dpt,
            currentPage: 1, //-----当前页码
            pageSize: 100, //-----每页条数
            sortOrderBy: 'DESC',
            sortPropName: 'create_time'
          }
          let requestList = {
            // 数字化覆盖现状
            status: coverApi.getCoverTargetList,
            // 数字化覆盖目标
            target: coverApi.getwfRptDgcalHrhxList
          }
          return requestList[this.type]({
            data: paramsData,
            type: this.fromPage
          }).then(res => {
            let data = res.data
            //
            let { records } = data.data
            if (!records || !records.length || !records.find(item => item.id == this.modelForm.code1)) {
              this.modelForm.code1 = null
              this.selectValue = null
            }
            this.associationTable = records || []
          })
        },
        hideFun() {
            this.$parent.hide()
        },
        //获取详情 
        async getStatusTargetOptions(){
          // 更换业务单元获取方式
            if (this.id) {
              this.pageLoading = true
              if (this.type == 'target') {
                await coverApi.getwfRptDgcalHrhxById({
                  data: {
                    id: this.id,
                  },
                  type: this.fromPage
                }).then(res => {
                  let info = res.data.data
                  this.modelForm = {
                    ...this.modelForm,
                    ...info,
                    tableCode: info.trgNode
                  }
                })
              } else {
                await coverApi.getCoverStatusById({
                  data: {
                    id: this.id,
                  },
                  type: this.fromPage
                }).then(res => {
                  let info = res.data.data
                  this.modelForm = {
                    ...this.modelForm,
                    ...info,
                    tableCode: info.trgNode
                  }
                })
      
              }
              let selectData = this.bussinessUnit.find(item => item.trgNode == this.modelForm.tableCode)
              if (selectData) {
                await coverApi.getRptTrgnodeTree({parentNodeCode: selectData.nodeId}).then(second => {
                  this.secondOrgan = second.data.data
                })
                let selecSecondtData = this.secondOrgan.find(item => item.nodeName == this.modelForm.company)
                if (selecSecondtData && selecSecondtData.nodeId) {
                  await coverApi.getRptTrgnodeTree({parentNodeCode: selecSecondtData.nodeId}).then(three => {
                    this.thirdOrgan = three.data.data
                  })
                }

              }
              this.$nextTick(() => {
                this.getTreeList(() => {
                  this.pageLoading = false
                })
              })
              
                          
            } else {
              let selectData = this.bussinessUnit.find(item => item.trgNode == this.modelForm.tableCode)
              if (selectData) {
                coverApi.getRptTrgnodeTree({parentNodeCode: selectData.nodeId}).then(second => {
                  this.secondOrgan = second.data.data
                })
              }
              this.pageLoading = false
              // this.getListByCode()
            }
        },
         //二级组织
        changetableCode(item) {
            // 更换业务单元获取方式
            if (this.useApiGetData) {
              coverApi.getRptTrgnodeTree({parentNodeCode: item.nodeId}).then(second => {
                  this.secondOrgan = second.data.data;
                  this.modelForm.company = '';
                  this.thirdOrgan = [];
                  this.modelForm.dpt = ''
              })
            } else {
              this.secondOrgan = item.children
              this.modelForm.company = ''
              this.thirdOrgan = [];
              this.modelForm.dpt = ''
            }
            this.$nextTick(() => {
              this.getTreeList()
            })

        },
        //三级组织
        changecompany(item){
            // 更换业务单元获取方式
            coverApi.getRptTrgnodeTree({parentNodeCode: item.nodeId}).then(second => {
                this.thirdOrgan = second.data.data;
                if (this.modelForm.dpt) {
                  this.modelForm.dpt = ''
                  this.$nextTick(() => {
                    this.getListByCode()
                  })
                }
            })       
        },
       
       //targe
        updateTarget(data, content){
            this.disabledAction = true
            coverApi.updatewfRptDgcalHrhx({
              type: this.fromPage,
              data}).then(() => {
                    this.$Message.success({
                        content: content,
                        duration: 3
                    });
                    this.$emit('Close', true)
                }) .finally(() => {
                  this.disabledAction = false
                })
        },
        addTarget(data,content){
            this.disabledAction = true
            coverApi.addwfRptDgcalHrhx(data).then(() => {
                this.$Message.success({
                    content: content,
                    duration: 3
                });
                this.$emit('Close', true)
                }).finally(() => {
                  this.disabledAction = false
                })
        },
        //status
        updateStatus(data, content){
            this.disabledAction = true
            coverApi.updateCoverRate({
              type: this.fromPage,
              data
            }).then(() => {
                this.$Message.success({
                    content: content,
                    duration: 3
                });
                this.$emit('Close', true)
            }).finally(() => {
              this.disabledAction = false
            })
        },
        addStatus(data,content){
            this.disabledAction = true
            coverApi.addCoverRate(data).then(() => {
                    this.$Message.success({
                        content: content,
                        duration: 3
                    });
                      this.$emit('Close', true)
                    }).finally(() => {
                      this.disabledAction = false
                    })
        },
        save(btnType) {
           this.$refs["editForm"].validate(valid => {
                    if (valid) {
                        this.modelForm.wfStatus = this.modelForm.wfStatus == 3 ? this.modelForm.wfStatus : btnType;
                        this.modelForm.trgNode = this.modelForm.tableCode;
                        delete this.modelForm.updateTime
                        delete this.modelForm.updateBy
                        if (this.type == 'target') {
                          if (this.id) {
                              // 编辑保存接口
                               if(this.dataStatus == 2 && this.modelForm.wfStatus == 1){
                                    this.$confirm({
                                        title:"撤回提交",
                                        content: "确认撤回提交?"
                                        }).then(()=>{
                                          this.updateTarget(this.modelForm,'撤回成功')
                                        })
                                    } else {
                                        if(this.modelForm.wfStatus == 2){
                                        this.$confirm({
                                            title:"提交",
                                            content: "确认提交?"
                                            }).then(()=>{
                                            this.updateTarget(this.modelForm,'提交成功')
                                            })
                                        } else {
                                            this.updateTarget(this.modelForm,'编辑成功')
                                        }
                                    }
                            
                          } else {
                                if(this.modelForm.wfStatus == 2){
                                this.$confirm({
                                    title:"提交",
                                    content: "确认提交?"
                                    }).then(()=>{
                                    this.addTarget(this.modelForm,'提交成功')
                                    })
                                } else {
                                    this.addTarget(this.modelForm,'新增成功')
                                }
                          }
                        } else {
                          if (this.id) {
                              // 编辑保存接口
                              if(this.dataStatus == 2 && this.modelForm.wfStatus == 1){
                                    this.$confirm({
                                        title:"撤回提交",
                                        content: "确认撤回提交?"
                                        }).then(()=>{
                                        this.updateStatus(this.modelForm, '撤回成功')
                                        })    //1待提交 2待审核 3通过 4.驳回
                                    } else {
                                         if(this.modelForm.wfStatus == 2){
                                            this.$confirm({
                                                title:"提交",
                                                content: "确认提交?"
                                                }).then(()=>{
                                                this.updateStatus(this.modelForm,'提交成功')
                                                })
                                            } else {
                                                this.updateStatus(this.modelForm,'编辑成功')
                                            }
                                    }
                          } else {
                              // 新增保存接口
                              if(this.modelForm.wfStatus == 2){
                                this.$confirm({
                                    title:"提交",
                                    content: "确认提交?"
                                    }).then(()=>{
                                    this.addStatus(this.modelForm,'提交成功')
                                    })
                                } else {
                                    this.addStatus(this.modelForm,'新增成功')
                                }
                          }
                        }
                       

                    } else {
                    this.$Message.error({
                        content: '请完善表单信息',
                        duration: 3
                    });
                        return 0;
                    }
                });
            },
         exportExcel() {
        //导入
        },
    }
}
</script>

<style lang="less" scoped>
/deep/.ivu-btn-warning {
    padding: 4px 23px;
    border-color: #ff6f4b;
    border-radius: 0;
    background-color: #ff6f4b;
}
.plan-edit-box {
  display: flex;
  overflow: hidden;
  flex-direction: column;
  height: 100%;
  .plan-page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    height: 60px;
    .header-title {
      font-weight: bold;
      font-size: 16px;
    }
  }
  .plan-page-content {
    overflow-x: hidden;
    overflow-y: scroll;
    flex: 1;
    padding: 0 20%;
  }
  
  
}
/deep/.ivu-col {
    padding: 0 60px!important;
}
/deep/.ivu-form .ivu-form-item-label {
    text-align: left;
}
.p1{
    margin-left: 28px;
    font-size: large;
    
}
.p2{
    margin-left: 42px;
    font-size: medium;
    

}
/deep/.ivu-select-small .ivu-select-input, .ivu-select-small.ivu-select-multiple .ivu-select-input {
    top: 0px;
  height: 32px;
    line-height: 32px;
}
/deep/.ivu-select-selected-value, 
/deep/.ivu-input-disabled, 
/deep/.ivu-input-number-input {
  color: #666666;
}
.disableFontcolor {
  /deep/.ivu-select-selected-value, 
  /deep/.ivu-input-disabled, 
  /deep/.ivu-input-number-input,
  /deep/.ivu-select-placeholder,
  /deep/.ivu-select-input
  {
    -webkit-text-fill-color: #666666;
  }
}
</style>
